package com.lotso.web.common.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Objects;

/**
 * ClassName: UserUtil
 * Description: 登录用户获取工具
 * Date: 2018/9/3 15:01 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class UserUtil {

    /**
     * 获取用户对象
     *
     * @return
     */
    public static UserDetails getPrincipal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!Objects.isNull(authentication)) {
            Object principal = authentication.getPrincipal();
            if (!Objects.isNull(principal) && principal instanceof UserDetails) {
                return (UserDetails) principal;
            }
        }
        return null;
    }

    /**
     * 获取用户名
     *
     * @return
     */
    public static String getPrincipalName() {
        String userName = null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!Objects.isNull(authentication)) {
            Object principal = authentication.getPrincipal();
            if (!Objects.isNull(principal) && principal instanceof UserDetails) {
                userName = ((UserDetails) principal).getUsername();
            } else {
                userName = principal.toString();
            }
        }
        return userName;
    }
}
